<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/31
 * Time: 19:25
 */

if (!(defined('IN_IA')))
{
    exit('Access Denied');
}
class orderfinish_MxShopPage extends WebPage
{
    public function main()
    {

        global $_W, $_GPC;

        $orderid = $_GPC['id'];
        if(empty($orderid)){
            show_json(0, '参数有误');
        }

        $order = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_service_order') . ' WHERE id=:id AND deleted=0 AND userdeleted=0', array(':id'=>$orderid));
        if(empty($order)){
            show_json(0, '订单不存在');
        }

        if($order['status'] != 2 || $order['ispay'] != 1){
            show_json(0,'订单未支付');
        }

        $price = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_service_goods_type_price') . ' WHERE id=:id', array(':id'=>$order['price_id']));
        if(empty($price)){
            show_json(0,'价格套餐不存在');
        }

//        if(time() < ($order['paytime'] + ($price['usetime']*60))){
//            show_json(0,'订单未完成喔');
//        }

        $goods = pdo_fetch('SELECT id, docking_number as number, isnormal  FROM ' . tablename('mx_shop_service_goods') . ' WHERE id=:id', array(':id'=>$order['goods_id']));
//        if($goods['isnormal'] != 2){
//            show_json(0, '设备不在工作中');
//        }
        $res = $this->orderPayBonus($order);
        //分红失败
        if(!$res){

        }

        $ret = m('iotswitch')->close($goods['number']);
        $this->goodsOpenLog($goods['number'], $order['ordersn'], 'close', $ret, 'web:sorder/orderfinish/main', '后台点击订单完成关闭设备；分红：'.$res);

        show_json(1, '订单已完成');

    }

    /*
    * 佣金提醒通知
    * @param string $uid 用户uid
    * @param string $url 详情链接
    * @param int $type 1佣金/2推荐/3消费者
    * @return bool
    */
    protected function sendNotice($uid, $url='', $type=1, $mendian='', $price=0, $time=0, $comm=0, $nickname=''){

        global $_W;
        $notice = pdo_fetch('SELECT * FROM '.tablename('mx_shop_service_notice').' WHERE 1');

        $date = date('Y-m-d H:i', $time);
        $msg = array();
        if($type == 1){

            $commission = unserialize($notice['commission']);
            $title = $commission['title'];
            $content = $commission['content'];

            if(!empty($content)){
                $content = str_replace('[门店]', $mendian, $content);
                $content = str_replace('[时间]', $date, $content);
                $content = str_replace('[消费金额]', $price, $content);
                $content = str_replace('[佣金]', $comm, $content);
            }

        }elseif($type == 2){

            $tuijian = unserialize($notice['tuijian']);
            $title = $tuijian['title'];
            $content = $tuijian['content'];

            if(!empty($content)){
                $content = str_replace('[门店]', $mendian, $content);
                $content = str_replace('[时间]', $date, $content);
                $content = str_replace('[消费金额]', $price, $content);
                $content = str_replace('[积分]', $comm, $content);
            }

        }elseif($type == 3){

            $xiaofei = unserialize($notice['xiaofei']);
            $title = $xiaofei['title'];
            $content = $xiaofei['content'];

            if(!empty($content)){
                $content = str_replace('[门店]', $mendian, $content);
                $content = str_replace('[时间]', $date, $content);
                $content = str_replace('[消费金额]', $price, $content);
                $content = str_replace('[积分]', $comm, $content);
            }
        }

        if(!empty($title)){
            if(empty($content)){

                $msg = $title;

            }else{

                $msg = $title . "\n\n" . $content;

            }
        }

        if(empty($msg)){
            return false;
        }

        m('message')->sendCustomNotice($uid, $msg, $url);

        return true;

    }

    protected function orderPayBonus($order=array()){

        global $_W, $_GPC;

        if(empty($order)){
            show_json(0,'订单不存在');
        }

        //分红比例
        $realmoney = $order['price'];
        $bonus = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_service_goods_type_bonus') . ' WHERE type_id=(SELECT type_id FROM '.tablename('mx_shop_service_goods').' WHERE id=:id)', array(':id'=>$order['goods_id']));
        if(empty($bonus)){
            $this->reserved($order['id'], $order['ordersn'], 0, 0, $realmoney);

            pdo_update('mx_shop_service_goods', array('isnormal'=>1), array('id'=>$order['goods_id']));

            pdo_update('mx_shop_service_order', array('status'=>3, 'upstatus'=>2, 'finishtime'=>time()), array('id'=>$order['id']));
            return true;
        }

        $bonus['chuangye'] = round($bonus['chuangye'], 2);
        $bonus['dianzhu'] = round($bonus['dianzhu'], 2);
        $bonus['qudao'] = round($bonus['qudao'], 2);
        $bonus['shengji'] = round($bonus['shengji'], 2);
        $bonus['quyu'] = round($bonus['quyu'], 2);
        $bonus['tuijian'] = round($bonus['tuijian'], 2);
        $bonus['tuijian2'] = round($bonus['tuijian2'], 2);
        $bonus['tuijian3'] = round($bonus['tuijian3'], 2);
        $bonus['xiaofei'] = round($bonus['xiaofei'], 2);
        $bonus['jishu'] = round($bonus['jishu'], 2);
        $bonus['jiangjin'] = round($bonus['jiangjin'], 2);

        //创业者
        $owner = pdo_fetchall('SELECT * FROM ' . tablename('mx_shop_service_goods_owner') . ' WHERE goods_id=:id AND deleted=0', array(':id'=>$order['goods_id']));

        //门店
        $mendian = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_mendian') . ' WHERE id=:id AND deleted=0', array(':id'=>$order['mendian_id']));

        //渠道商
        //$channel = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_mendian_industry') . ' WHERE id=:id AND deleted=0', array(':id'=>$mendian['industryid']));
        $channel['channelid'] = $mendian['channelid'];

        //省运营商
        $province = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_operator') . ' WHERE type=1 AND deleted=0 AND province=:province', array( ':province'=>$mendian['province']));

        //区运营商
        $dist = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_operator') . ' WHERE type=2 AND deleted=0 AND province=:province AND city=:city AND dist=:dist', array( ':province'=>$mendian['province'], ':city'=>$mendian['city'], ':dist'=>$mendian['dist']));

        //消费者
        $member = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_user') . ' WHERE id=:id', array(':id'=>$order['uid']));

        if(!empty($owner) && !empty($bonus['chuangye'])){
            //创业者分红
            $ownerbonus = round((($bonus['chuangye'] / 100) * $order['price']), 2);
            foreach ($owner as $key=>$val){
                $money = 0;
                $money = round((($val['ratio'] / 100) * $ownerbonus), 2);
                $realmoney -= $money;
                $ratio = ($bonus['chuangye'] * $val['ratio']) / 100;
                $res = $this->setCommission($order['id'], $order['ordersn'], $money, $ratio, 1, $val['uid'],0,2);
                if ($res) {
                    $this->sendNotice($val['uid'], mobileUrl('commission/order', '', true), 1, $mendian['mendianname'], $order['price'], $order['createtime'], $money, $member['realname']);
                }
            }
        }

        //店主分红
        if(!empty($mendian['manageid']) && !empty($bonus['dianzhu'])) {
            $dzbonus = round((($bonus['dianzhu'] / 100) * $order['price']), 2);
            $realmoney -= $dzbonus;
            $res = $this->setCommission($order['id'], $order['ordersn'], $dzbonus, $bonus['dianzhu'], 2, 0, $mendian['id'],1);
            if ($res) {
                $this->sendNotice($mendian['manageid'], mobileUrl('mendian/orderlist', array('id' => $mendian['id']), true), 1, $mendian['mendianname'], $order['price'], $order['createtime'], $dzbonus, $member['realname']);
            }
        }

        //渠道商分红
        if(!empty($channel['channelid']) && !empty($bonus['qudao'])) {
            $qdbonus = round((($bonus['qudao'] / 100) * $order['price']), 2);
            $realmoney -= $qdbonus;
            $res = $this->setCommission($order['id'], $order['ordersn'], $qdbonus, $bonus['qudao'], 1, $channel['channelid'], 0,3);
            if ($res) {
                $this->sendNotice($channel['channelid'], mobileUrl('commission/order', '', true), 1, $mendian['mendianname'], $order['price'], $order['createtime'], $qdbonus, $member['realname']);
            }

        }

        if(!empty($province) && !empty($bonus['shengji'])){
            //省级运营商分红
            $sjbonus = round((($bonus['shengji'] / 100) * $order['price']), 2);
            $realmoney -= $sjbonus;
            $res = $this->setCommission($order['id'], $order['ordersn'], $sjbonus, $bonus['shengji'], 1, $province['uid'],0,4);
            if ($res) {
                $this->sendNotice($province['uid'], mobileUrl('commission/order', '', true), 1, $mendian['mendianname'], $order['price'], $order['createtime'], $sjbonus, $member['realname']);
            }
        }

        if(!empty($dist) && !empty($bonus['quyu'])){
            //区域运营商分红
            $qybonus = round((($bonus['quyu'] / 100) * $order['price']), 2);
            $realmoney -= $qybonus;
            $res = $this->setCommission($order['id'], $order['ordersn'], $qybonus, $bonus['quyu'], 1, $dist['uid'],0,5);
            if ($res) {
                $this->sendNotice($dist['uid'], mobileUrl('commission/order', '', true), 1, $mendian['mendianname'], $order['price'], $order['createtime'], $qybonus, $member['realname']);
            }
        }

        if(!empty($member['parentid']) && !empty($bonus['tuijian'])){

            //一级分销商
            $agent = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_user') . ' WHERE id=:id', array(':id'=>$member['parentid']));
            if(!empty($agent) && !empty($bonus['tuijian'])){

                $tjbonus = round((($bonus['tuijian'] / 100) * $order['price']), 2);
                $realmoney -= $tjbonus;

                //推荐门店
                if($agent['ismendian'] == 1){

                    $res = $this->setCommission($order['id'], $order['ordersn'], $tjbonus, $bonus['tuijian'], 2, 0, $agent['mendian_id'],6);
                    if($res) {
                        //门店
                        $mendian = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_mendian') . ' WHERE id=:id AND deleted=0', array(':id' => $agent['mendian_id']));
                        $this->sendNotice($mendian['manageid'], mobileUrl('mendian/orderlist', array('id' => $mendian['id']), true), 1, $mendian['mendianname'], $order['price'], $order['createtime'], $tjbonus, $member['realname']);
                    }

                }else {

                    $result = m('userinfo')->setCredit($agent['id'], 'credit2', $tjbonus, array($_W['member']['uid'], '推荐人返通用积分' . $tjbonus));
                    if (!is_error($result)) {
                        $log = array('uniacid' => $_W['platformid'], 'logno' => $order['ordersn'], 'title' => 'CGC下级消费推荐人返通用积分', 'uid' => $agent['id'], 'money' => $tjbonus, 'type' => 3, 'createtime' => time(), 'status' => 1, 'couponid' => 0);
                        pdo_insert('mx_shop_user_log', $log);

                        $this->sendNotice($agent['id'], mobileUrl('member/log', '', true), 2, $mendian['mendianname'], $order['price'], $order['createtime'], $tjbonus, $member['realname']);
                    }

                    //二级分销商
                    if (!empty($agent['parentid'])) {

                        $agent2 = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_user') . ' WHERE id=:id', array(':id' => $agent['parentid']));
                        if (!empty($agent2) && !empty($bonus['tuijian2'])) {

                            $tj2bonus = round((($bonus['tuijian2'] / 100) * $order['price']), 2);
                            $realmoney -= $tj2bonus;

                            //推荐门店
                            if($agent2['ismendian'] == 1){

                                $res = $this->setCommission($order['id'], $order['ordersn'], $tj2bonus, $bonus['tuijian2'], 2, 0, $agent2['mendian_id'],6);
                                if($res) {
                                    //门店
                                    $mendian = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_mendian') . ' WHERE id=:id AND deleted=0', array(':id' => $agent2['mendian_id']));
                                    $this->sendNotice($mendian['manageid'], mobileUrl('mendian/orderlist', array('id' => $mendian['id']), true), 1, $mendian['mendianname'], $order['price'], $order['createtime'], $tj2bonus, $member['realname']);
                                }

                            }else {

                                $result = m('userinfo')->setCredit($agent2['uid'], 'credit2', $tj2bonus, array($_W['member']['uid'], '推荐人返通用积分' . $tj2bonus));
                                if (!is_error($result)) {
                                    $log = array('uniacid' => $_W['platformid'], 'logno' => $order['ordersn'], 'title' => 'CGC下级消费推荐人返通用积分', 'uid' => $agent2['uid'], 'money' => $tj2bonus, 'type' => 3, 'createtime' => time(), 'status' => 1, 'couponid' => 0);
                                    pdo_insert('mx_shop_user_log', $log);

                                    $this->sendNotice($agent2['uid'], mobileUrl('member/log', '', true), 2, $mendian['mendianname'], $order['price'], $order['createtime'], $tj2bonus, $member['realname']);
                                }

                                //三级分销商
                                if (!empty($agent2['parentid'])) {
                                    $agent3 = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_user') . ' WHERE id=:id', array(':id' => $agent2['parentid']));
                                    if (!empty($agent3) && !empty($bonus['tuijian3'])) {

                                        $tj3bonus = round((($bonus['tuijian3'] / 100) * $order['price']), 2);
                                        $realmoney -= $tj3bonus;

                                        //推荐门店
                                        if($agent3['ismendian'] == 1){

                                            $res = $this->setCommission($order['id'], $order['ordersn'], $tj3bonus, $bonus['tuijian3'], 2, 0, $agent3['mendian_id'],6);
                                            if($res) {
                                                //门店
                                                $mendian = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_mendian') . ' WHERE id=:id AND deleted=0', array(':id' => $agent3['mendian_id']));
                                                $this->sendNotice($mendian['manageid'], mobileUrl('mendian/orderlist', array('id' => $mendian['id']), true), 1, $mendian['mendianname'], $order['price'], $order['createtime'], $tj3bonus, $member['realname']);
                                            }

                                        }else {
                                            $result = m('userinfo')->setCredit($agent3['uid'], 'credit2', $tj3bonus, array($_W['member']['uid'], '推荐人返通用积分' . $tj3bonus));
                                            if (!is_error($result)) {
                                                $log = array('uniacid' => $_W['platformid'], 'logno' => $order['ordersn'], 'title' => 'CGC下级消费推荐人返通用积分', 'uid' => $agent3['uid'], 'money' => $tj3bonus, 'type' => 3, 'createtime' => time(), 'status' => 1, 'couponid' => 0);
                                                pdo_insert('mx_shop_user_log', $log);

                                                $this->sendNotice($agent3['uid'], mobileUrl('member/log', '', true), 2, $mendian['mendianname'], $order['price'], $order['createtime'], $tj3bonus, $member['realname']);
                                            }
                                        }

                                    }
                                }

                            }

                        }
                    }

                }

            }
        }

        //消费者
        if(!empty($bonus['xiaofei'])) {
            $xfbonus = round((($bonus['xiaofei'] / 100) * $order['price']), 2);
            $realmoney -= $xfbonus;
            $result = m('userinfo')->setCredit($order['uid'], 'credit2', $xfbonus, array($_W['member']['uid'], '消费者返通用积分' . $xfbonus));
            if (!is_error($result)) {
                $log = array('uniacid' => $_W['platformid'], 'logno' => $order['ordersn'], 'title' => 'CGC消费者返通用积分', 'uid' => $order['uid'], 'money' => $xfbonus, 'type' => 4, 'createtime' => time(), 'status' => 1, 'couponid' => 0);
                pdo_insert('mx_shop_user_log', $log);

                $this->sendNotice($order['uid'], mobileUrl('member/log', '', true), 3, $mendian['mendianname'], $order['price'], $order['createtime'], $xfbonus, $member['realname']);
            }
        }

        //技术
        $jsbonus = 0;
        if(!empty($bonus['jishu'])) {
            $jsbonus = number_format((($bonus['jishu'] / 100) * $order['price']), 2);
            $realmoney -= $jsbonus;
        }

        //奖金池
        $jjbonus = 0;
        if(!empty($bonus['jiangjin'])) {
            $jjbonus = number_format((($bonus['jiangjin'] / 100) * $order['price']), 2);
            $realmoney -= $jjbonus;
        }
        $remain= 0;
        if($realmoney > 0){
            $remain = $realmoney;
        }
        $this->reserved($order['id'], $order['ordersn'], $jsbonus, $jjbonus, $remain);

        pdo_update('mx_shop_service_goods', array('isnormal'=>1), array('id'=>$order['goods_id']));

        pdo_update('mx_shop_service_order', array('status'=>3, 'upstatus'=>2, 'finishtime'=>time()), array('id'=>$order['id']));

        return true;
    }

    protected function reserved($oid, $osn, $jishu=0, $jiangjin=0, $remain=0){

        global $_W;

        if(empty($jiangjin) && empty($jishu)){
            return false;
        }

        $reserved = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_service_commission_reserved') . ' WHERE 1 LIMIT 1');
        if(empty($reserved)){

            $data = array(
                'uniacid' => $_W['platformid'],
                'jishu' => $jishu,
                'jiangjin' => $jiangjin,
                'remain' => $remain,
                'createtime' => time(),
                'updatetime' => time(),
            );

            pdo_insert('mx_shop_service_commission_reserved', $data);

        }else{

            $updata = array(
                'jishu' => $reserved['jishu'] + $jishu,
                'jiangjin' => $reserved['jiangjin'] + $jiangjin,
                'remain' => $reserved['remain'] + $remain,
                'updatetime' => time(),
            );

            pdo_update('mx_shop_service_commission_reserved', $updata, array('id'=>$reserved['id']));
        }

        $log = array(
            'uniacid' => $_W['platformid'],
            'orderid' => $oid,
            'ordersn' => $osn,
            'jishu' => $jishu,
            'jiangjin' => $jiangjin,
            'remain' => $remain,
            'type' => 1,
            'description' => '用户消费佣金预留',
            'createtime' => time()
        );
        pdo_insert('mx_shop_service_commission_reserved_log',$log);

        return true;
    }

    protected  function setCommission($orderid, $ordersn, $money, $ratio, $type=1, $uid=0, $mendianid=0, $level=0){

        global $_W;

        if(empty($money)){
            return false;
        }

        if($type != 1 && $mendianid == 0){
            return false;
        }

        if($type == 1){
            $condition = ' AND uid="'.$uid.'"';
        }else{
            $condition = ' AND mendianid='.intval($mendianid);
        }

        $comm = pdo_fetch('SELECT * FROM ' . tablename('mx_shop_service_commission') . ' WHERE 1'.$condition);
        if(empty($comm)){

            $data = array(
                'uniacid' => $_W['platformid'],
                'total' => $money,
                'remain' => $money,
                'drawal' => 0,
                'createtime' => time(),
                'updatetime'=> time(),
            );

            if($type == 1){
                $data['uid'] = $uid;
                $data['type'] = $type;
                $data['mendianid'] = 0;
            }else{
                $data['uid'] = 0;
                $data['type'] = $type;
                $data['mendianid'] = $mendianid;

            }
            pdo_insert('mx_shop_service_commission', $data);
            $comm['id'] = pdo_insertid();

        }else{

            $updata = array(
                'total'=> $comm['total'] + $money,
                'remain'=> $comm['remain'] + $money,
                'updatetime'=> time(),
            );

            pdo_update('mx_shop_service_commission', $updata, array('id'=>$comm['id']));
        }

        $log = array(
            'uniacid' => $_W['platformid'],
            'orderid' => $orderid,
            'ordersn' => $ordersn,
            'comid' => $comm['id'],
            'type' => 1,
            'level' => $level,
            'isfinish' => 1,
            'finishtime' => time(),
            'money' => $money,
            'ratio' => $ratio,
            'description' => '用户消费获得佣金',
            'createtime' => time(),
        );

        if($type == 1){
            $log['uid'] = $uid;
            $log['mendianid'] = 0;
        }else{
            $log['uid'] = 0;
            $log['mendianid'] = $mendianid;
        }

        pdo_insert('mx_shop_service_commission_log', $log);

        return true;

    }

    protected function goodsOpenLog($goodsnumber, $ordersn, $type='open', $ret=true, $location, $cause=''){

        header("Content-type: text/html; charset=utf-8");

        $file = '../addons/mx_shop/core/web/sorder/log/log--'.date('Y-m-d', time()).'.txt';

        $open = '';
        $res = $ret ? '成功' : '失败';
        switch ($type){
            case 'open':
                $open = '启动';
                break;
            case 'check':
                $open = '检测';
                break;
            case 'close':
                $open = '关闭';
                break;
        }

        $log = date('Y-m-d H:i:s', time()).' ：'.$open.'设备'.$res.'! '.$cause.'! 设备编号：'.$goodsnumber.' ，订单号：'.$ordersn." ! 位置：{$location} \r\n";

        if($f  = file_put_contents($file, $log,FILE_APPEND)){
            return true;
        }else{
            return false;
        }

    }

}